﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;

namespace YoProgramo.Infrastructure.Tools.PagedList
{
    public class PagedList<T> : List<T>, IPagedList<T>
    {
        public PagedList(IEnumerable<T> superset, int index, int pageSize)
        {
            var source = superset == null
                             ? new List<T>().AsQueryable()
                             : superset.AsQueryable();

            TotalItemCount = source.Count();
            PageSize = pageSize;
            PageIndex = index;
            if (TotalItemCount > 0)
                PageCount = (int) Math.Ceiling(TotalItemCount/(double) PageSize);
            else
                PageCount = 0;

            if (index < 0)
                throw new ArgumentOutOfRangeException("index", index, "PageIndex cannot be below 0.");
            if (pageSize < 1)
                throw new ArgumentOutOfRangeException("pageSize", pageSize, "PageSize cannot be less than 1.");

            // add items to internal list
            if (TotalItemCount > 0)
                if (index == 0)
                    AddRange(source.Take(pageSize).ToList());
                else
                    AddRange(source.Skip((index) * pageSize).Take(pageSize).ToList());
        }

        #region IPagedList<T> Members
        public int PageCount { get; private set; }
        public int TotalItemCount { get; private set; }
        public int PageIndex { get; private set; }
        public int PageNumber
        {
            get { return PageIndex + 1; }
        }
        public int PageSize { get; private set; }
        public bool HasPreviousPage
        {
            get { return PageIndex > 0; }
        }

        public bool HasNextPage
        {
            get { return PageIndex < (PageCount - 1); }
        }

        public bool IsFirstPage
        {
            get { return PageIndex <= 0; }
        }

        public bool IsLastPage
        {
            get { return PageIndex >= (PageCount - 1); }
        }

        #endregion
    }
}